package com.newlink.building.login.mvp.model

import android.util.Log
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.newlink.building.login.mvp.contract.Module_Login_LoginContract
import com.newlink.building.common_base.base.BaseModel
import com.newlink.building.common_base.constant.Base_Constant.FANVIL_RUL
import com.newlink.building.common_base.http.Base_RetrofitHelper
import com.newlink.building.common_base.http.exception.Base_ErrorStatus
import com.newlink.building.common_base.model.bean.AppConfigData
import com.newlink.building.common_base.model.bean.FcmsInfoData
import com.newlink.building.common_base.model.bean.HttpResult
import com.newlink.building.common_base.model.bean.KcpInfoData
import com.newlink.building.common_base.model.bean.LoginMsgCodeBean
import com.newlink.building.common_base.model.bean.LoginRequestBean
import com.newlink.building.common_base.model.bean.LoginResponseData
import com.newlink.building.common_base.model.bean.LoginSipAccountRequestBean
import com.newlink.building.common_base.model.bean.PolicyAgreementData
import com.newlink.building.common_base.model.bean.ResponseTopData
import com.newlink.building.common_base.model.bean.SipRequest
import com.newlink.building.common_base.model.bean.UserInfoData
import com.newlink.building.common_base.model.bean.VerifyCodeRequest
import com.newlink.building.obfuscation.Module_Obfuscation_ObfuscationHelper
import com.newlink.building.obfuscation.Module_Obfuscation_ObfuscationInvoker
import io.reactivex.Observable
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException


/**
 * Created by xiaodong on 2022/8/24.
 */
class Module_Login_LoginModel : BaseModel(), Module_Login_LoginContract.Model {

    override fun login(bean: LoginRequestBean): Observable<HttpResult<LoginResponseData>> {
        // 登录数据模型请求时的混淆
        Module_Obfuscation_ObfuscationHelper.beforeNetworkRequest("LOGIN_MODEL", mapOf(bean.username to bean.password))
        Module_Obfuscation_ObfuscationInvoker.invokeRandom(bean.hashCode())

        return Base_RetrofitHelper.service.login(bean = bean)
    }

    override fun loginWithQR(
        userName: String,
        password: String,
    ): Observable<HttpResult<LoginResponseData>> {
        return Base_RetrofitHelper.service.loginWithQR(userName, password)
    }

    override fun loginWithSipAccount(bean: LoginSipAccountRequestBean): Observable<HttpResult<LoginResponseData>> {
        return Base_RetrofitHelper.service.loginBySip(bean)
    }

    override fun getUserInformation(
        token: String,
        userId: Long,
    ): Observable<HttpResult<UserInfoData>> {
        // 获取用户信息时的混淆
        Module_Obfuscation_ObfuscationHelper.beforeDatabaseOperation("USER_INFO", userId.toString())
        Module_Obfuscation_ObfuscationInvoker.invokeSpecific(2, userId)

        return Base_RetrofitHelper.service.getUserInfo(token, userId)
    }

    override fun getUserInfo(token: String, userId: Long): Observable<HttpResult<UserInfoData>> {
        return Base_RetrofitHelper.service.getUserInfo(token, userId)
    }

    override fun getKcpInformation(
        token: String,
        userId: Long,
    ): Observable<HttpResult<KcpInfoData>> {
        return Base_RetrofitHelper.service.getKcpInfo(token, userId)
    }

    override fun getAppConfig(token: String): Observable<HttpResult<AppConfigData>> {
        return Base_RetrofitHelper.service.getAppConfig(token)
    }

    override fun requestSipRegister(data: SipRequest) {
    }

    override fun getVerifyCode(
        area: String,
        phoneNum: String,
        userCategory: Int,
    ): Observable<HttpResult<ResponseTopData>> {
//        return RetrofitHelper.service.getVerifyCode(area, phoneNum)
        return Base_RetrofitHelper.service.getKitVerifyCode(
            VerifyCodeRequest(
                area = area,
                mobile = phoneNum,
                login = true,
                type = 1,
                userCategory = userCategory
            )
        )
    }

    override fun loginWithMsgCode(bean: LoginMsgCodeBean): Observable<HttpResult<LoginResponseData>> {
        // 短信验证码登录时的混淆
        Module_Obfuscation_ObfuscationInvoker.invokeRandom("msg_code_login")

        return Base_RetrofitHelper.service.loginWithMsgCode(bean)
    }

    override fun getFcmsInfoList(
        region: String,
        language: String,
    ): Observable<HttpResult<MutableList<FcmsInfoData>>> {
        return Observable.create { emitter ->
            val buildType = "2" // neutral渠道固定值
            // 创建 OkHttpClient 并添加拦截器来设置 header
            val okHttpClient = OkHttpClient.Builder()
                .addInterceptor { chain ->
                    val original = chain.request()
                    val requestBuilder = original.newBuilder()
                        .header("System-Type", buildType) // 替换为实际的 header 名称和值
                    val request = requestBuilder.build()
                    chain.proceed(request)
                }.build()
            val request = Request.Builder().url("$FANVIL_RUL?a=$region&lan=$language").build()
            Log.d("getFcmsInfoList", "$FANVIL_RUL?a=$region&lan=$language")

            okHttpClient.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    emitter.onError(e)
                }

                override fun onResponse(call: Call, response: Response) {
                    Log.d("getFcmsInfoList", "HTTP Status Code: ${response.code}")
                    if (!response.isSuccessful) {
                        Log.d("getFcmsInfoList", "HTTP error: ${response.code} ${response.message}")
                        emitter.onError(IOException("HTTP error: ${response.code} ${response.message}"))
                        return
                    }

                    val jsonStr = response.body?.string()
                    Log.d("getFcmsInfoList", "Response body: $jsonStr")
                    var data = mutableListOf<FcmsInfoData>()
                    try {
                        data = Gson().fromJson(
                            jsonStr,
                            object :
                                TypeToken<MutableList<FcmsInfoData>>() {}.type
                        ) as MutableList<FcmsInfoData>
                        val result = HttpResult(data)
                        result.code = Base_ErrorStatus.SUCCESS
                        emitter.onNext(result)
                    } catch (e: Exception) {
                        Log.e("getFcmsInfoList", "JSON parsing error: ${e.message}")
                        emitter.onError(e)
                    }
                    emitter.onComplete()
                }
            })
        }
    }

    override fun getAgreement(): Observable<HttpResult<PolicyAgreementData>> {
        return Base_RetrofitHelper.xLinkService.getAgreement()
    }

}